package cn.com.twoke.app.pin_dou_dou.utils;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 无损图像操作工具类
 */
public class ImageLossLessUtils {

    /**
     * 无损保存图像
     * @param sourceImgPath 源文件路径
     * @param targetImgPath 目标文件路径
     * @param suffix 文件格式
     * @throws Exception 图像保存过程中发生错误时抛出
     */
    public static void saveLossLessImage(String sourceImgPath, String targetImgPath, String suffix) throws Exception {
        BufferedImage image = ImageIO.read(new File(sourceImgPath));
        saveLossLessImage(image, targetImgPath, suffix);
    }

    /**
     * 无损保存BufferedImage对象
     * @param image BufferedImage对象
     * @param targetImgPath 目标文件路径
     * @param suffix 文件格式
     * @throws Exception 图像保存过程中发生错误时抛出
     */
    public static void saveLossLessImage(BufferedImage image, String targetImgPath, String suffix) throws Exception {
        // 不压缩图片质量进行保存
        ImageWriter writer = ImageIO.getImageWritersBySuffix(suffix).next();
        ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        // 0-1范围，值越大质量越高
        imageWriteParam.setCompressionQuality(1);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        writer.setOutput(new MemoryCacheImageOutputStream(output));
        writer.write(null, new IIOImage(image, null, null), imageWriteParam);
        writer.dispose();
        // 最终图片保存路径
        FileOutputStream file = new FileOutputStream(targetImgPath);
        file.write(output.toByteArray());
        file.close();
        output.close();
    }

}